package com.ruoyi.stuclient.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.stuclient.domain.EwcSmsFlow;
import com.ruoyi.stuclient.domain.dto.SMSGetDto;
import com.ruoyi.stuclient.domain.dto.StudentResetPwdDto;
import com.ruoyi.stuclient.mapper.EwcSmsFlowMapper;
import com.ruoyi.stuclient.service.IEwcSmsFlowService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;
import java.util.UUID;

/**
 * 短信模板信息Service业务层处理
 *
 * @author zsp
 * @date 2025-05-01
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class EwcSmsFlowServiceImpl extends MPJBaseServiceImpl<EwcSmsFlowMapper, EwcSmsFlow> implements IEwcSmsFlowService {
    //单次获取短信允许验证错误失败次数
    @Value("${sms.SMSCodeErrorCountLimit}")
    private Integer SMSCodeErrorCountLimit;

    //单次验证码有效时间 单位ms
    @Value("${sms.SMSCodeGapTimeLimit}")
    private Integer SMSCodeGapTimeLimit;

    @Override
    public String saveSMSCode(SMSGetDto smsGetDto, String mobileNo, String smsCode, String templateContent, String requestId) {
        EwcSmsFlow ewcSmsFlow = new EwcSmsFlow();
        String flowId = UUID.randomUUID().toString().replace("-", "");
        ewcSmsFlow.setId(flowId);
        ewcSmsFlow.setClientNo(smsGetDto.getClientNo());
        ewcSmsFlow.setMobileNo(mobileNo);
        ewcSmsFlow.setSmsCode(smsCode);
        ewcSmsFlow.setSmsValidateStt("2");
        ewcSmsFlow.setTemplateId(smsGetDto.getTemplateId());
        ewcSmsFlow.setSmsContent(templateContent.replace("verifyCode",smsCode));
        Date currentDate = new Date();
        ewcSmsFlow.setCreateTime(currentDate);
        ewcSmsFlow.setSendTime(currentDate);
        ewcSmsFlow.setUpdateTime(currentDate);
        ewcSmsFlow.setRequestId(requestId);
        return this.save(ewcSmsFlow) ? flowId : "";
    }

    @Override
    public AjaxResult validateSMSCode(StudentResetPwdDto studentResetPwdDto) {
        UpdateWrapper<EwcSmsFlow> updateWrapper = new UpdateWrapper<>();
        // 设置更新条件
        updateWrapper.eq("id", studentResetPwdDto.getFlowId())
                .eq("client_no", studentResetPwdDto.getStudentNo());
        EwcSmsFlow entity = new EwcSmsFlow();

        //1.判断提交验证码是否存在
        EwcSmsFlow ewcSmsFlow = this.getOne(Wrappers.<EwcSmsFlow>lambdaQuery().eq(EwcSmsFlow::getId, studentResetPwdDto.getFlowId())
                   .eq(EwcSmsFlow::getClientNo, studentResetPwdDto.getStudentNo()));
        if(ewcSmsFlow == null){
            return AjaxResult.error("验证码不存在");
        }
        //2.判断当前验证流水次数是否超过单次获取短信允许验证错误失败次数
        if(ewcSmsFlow.getSmsErrorCount() >= SMSCodeErrorCountLimit){
            return AjaxResult.error(String.format("验证码错误超过%s次，请重新获取", SMSCodeErrorCountLimit));
        }
        //3.根据状态判断验证码是否有效
        if(!Objects.equals("2",ewcSmsFlow.getSmsValidateStt()) && !Objects.equals("3",ewcSmsFlow.getSmsValidateStt())){
            return AjaxResult.error("验证码已失效，请重新获取");
        }
        //4.判断验证码是否过期
        long GapTime = DateUtils.getNowDate().getTime() - ewcSmsFlow.getSendTime().getTime();
        System.out.println("GapTime:"+GapTime);
        if(GapTime > SMSCodeGapTimeLimit.longValue()){
            entity.setSmsValidateStt("5");
            this.update(entity,updateWrapper);
            return AjaxResult.error("验证码已过期，请重新获取");
        }
        //5.校验验证码是否正确
        if(!Objects.equals(ewcSmsFlow.getSmsCode(),studentResetPwdDto.getVerifyCode())){
            entity.setSmsValidateStt("3");
            entity.setSmsErrorCount(ewcSmsFlow.getSmsErrorCount() + 1);
            this.update(entity,updateWrapper);
            return AjaxResult.error("验证码错误，请重新录入");
        }
        entity.setSmsValidateStt("4");
        this.update(entity,updateWrapper);
        return AjaxResult.success("校验成功");
    }
}
